package com.flk.oauth.endpoint;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.provider.endpoint.FrameworkEndpoint;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @author xxwy
 * on 2018/10/15 0015
 */
@FrameworkEndpoint
public class RevokeTokenEndpoint {

    private static final Logger logger = LoggerFactory.getLogger(RevokeTokenEndpoint.class);

    @Autowired
    @Qualifier("consumerTokenServices")
    ConsumerTokenServices consumerTokenServices;

    @RequestMapping(method = RequestMethod.DELETE, value = "/oauth/token")
    public ResponseEntity revokeToken(HttpServletRequest request, HttpServletResponse response, String access_token) {
        HashMap<String, Object> map = new HashMap<>();
        access_token = access_token == null? request.getParameter("access_token"):access_token;
        logger.info("access_token {}",access_token);
        if (consumerTokenServices.revokeToken(access_token)){
            map.put("body","注销成功");
            logger.info("注销成功");
            return ResponseEntity.ok(map);
        }else{
            map.put("body","注销失败");
            response.setHeader("Access-Control-Allow-Methods", "PUT,GET,POST,DELETE,OPTIONS");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept");
            return ResponseEntity.badRequest().body(map);
        }
    }
}
